//
//  UIChooseBleDev.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/14/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UIChooseBleDev.h"
#import "ViewController.h"

static NSString* _sCurrUuId = @"";
static NSString* _sCurBleConn = @"";


@implementation UIChooseBleDev {
    UIButton* _btnSyncData;
    UIImageView* _ivDropDownList;
    UILabel* _lblDrowDownList;
    NIDropDownList* _ddlBleDevice;
    
    NcitBleDevice* _ncitBleDev;
    BOOL _bChoseBleDev;
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //UIColor* colBkgd = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"ic-bottbkgd-t.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        //self.backgroundColor = colBkgd;
        self.backgroundColor = [UIColor colorWithWhite:0.25 alpha:0.75];
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = 5.0f;
        //_nSelBtn = -1;
        [self initialize: frame];
    }
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _ncitBleDev = pApp.m_ncitBleDev;
  _ncitBleDev.nDebugDataType = 1;
    
  return self;
}

- (void) initialize:(CGRect)frame
{
    CGFloat yPos = 15;
    CGFloat W = frame.size.width;
    //BOOL bIpad = frame.size.width > 500;
    
    CGFloat xPos = W - 50;
    UIImage* iBtn = [[UIImage imageNamed:@"btn-sync-g.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _btnSyncData = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnSyncData.frame = CGRectMake(xPos, yPos-4, 48, 48);
    [_btnSyncData setBackgroundImage:iBtn forState:UIControlStateNormal];
    [_btnSyncData addTarget:self action:@selector(tapStartSync:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_btnSyncData];
    _btnSyncData.hidden = YES;
    
    UIImage* iDorpDown = [UIImage imageNamed:@"ic-dropdown"];
    _ivDropDownList = [[UIImageView alloc] initWithFrame:CGRectMake(8, yPos+0, frame.size.width - 16, (frame.size.width - 16) / 315 * 38)];
    _ivDropDownList.image = iDorpDown;
    [self addSubview:_ivDropDownList];
    UITapGestureRecognizer *ivSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapDropDown)];
    ivSingleTap.numberOfTapsRequired = 1;
    [_ivDropDownList setUserInteractionEnabled:YES];
    [_ivDropDownList addGestureRecognizer:ivSingleTap];
    
    _lblDrowDownList = [[UILabel alloc] initWithFrame:CGRectMake(10, yPos+2, frame.size.width - 20, 30)];//frame.size.height - 5)];
    _lblDrowDownList.textColor = [UIColor grayColor];
    _lblDrowDownList.font = [UIFont systemFontOfSize: 16.0];
    _lblDrowDownList.backgroundColor = [UIColor clearColor];
    _lblDrowDownList.textAlignment = NSTextAlignmentLeft;
    _lblDrowDownList.text = NSLocalizedString(@"Tap to choose device", nil);
    [self addSubview:_lblDrowDownList];
    
    //dropdownlist
    xPos = 15;
    _ddlBleDevice = [[NIDropDownList alloc] initWithFrame:CGRectMake(xPos, yPos + 28, W-92, frame.size.height - 110) type:99];
    _ddlBleDevice.delegate = self;
    //_ncitBleDev.bleDelegate = self;
    [self addSubview:_ddlBleDevice];
}

-(void) tapStartSync:(id)sender
{
    ViewController* mainPage = [self findViewController:self];
    if(mainPage != nil) {
      _ncitBleDev.bleDelegate = nil;
      mainPage.m_bSyncStepData = YES;
      
      //_ncitBleDev.bSyncDevData = YES;
      _ncitBleDev.nDebugDataType = 1;
        
      if(_ncitBleDev.bConnBleDev) {
          [_ncitBleDev stopMeas];
      }
      _ncitBleDev.bJustScanDev = NO;
      [_ncitBleDev startScan:nil]; //@"FC00"];
      [self performSelector:@selector(delayOpenScanSheet) withObject:nil afterDelay:5.0f];
        
      _ncitBleDev.bleDelegate = self;
      _lblDrowDownList.text = NSLocalizedString(@"Scan PEDO. Waiting...", nil);
    }
}

-(void) onTapDropDown {
    _bChoseBleDev = NO;
  
    if([_ddlBleDevice isPopup]) {
        [_ncitBleDev stopScan];
        [_ddlBleDevice hideDropDownList];
        return;
    }
    
    ViewController* mainPage = [self findViewController:self];
    if(mainPage != nil)
        mainPage.m_bSyncStepData = NO;
    
    //[_ddlBleDevice setListData: nil curSel:@"0"]; 
    _ncitBleDev.bJustScanDev = NO;

    
    if(_ncitBleDev.bConnBleDev) {
        [_ncitBleDev stopMeas];
    }
    //_ncitBleDev.bSyncDevData = NO;
    [_ncitBleDev startScan:nil]; //@"FC00"];
    [self performSelector:@selector(delayOpenScanSheet) withObject:nil afterDelay:5.0f];
    
     _ncitBleDev.bleDelegate = self;
    _lblDrowDownList.text = NSLocalizedString(@"Scan PEDO. Waiting...", nil);
}

- (void) bleMgrDiscover:(CBPeripheral *)aPeripheral
{
    NSString* sBleName = aPeripheral.name;
    if(sBleName == nil || (![sBleName hasPrefix:@"PE"] && ![sBleName hasPrefix:@"COOBIT"]))
       return;
    
    //NSUInteger nCount = [_ncitBleDev connBLEDevCount:@"PE"];
    NSString * sInfo = [NSString stringWithFormat:@"%@", NSLocalizedString(@"Discovered...", nil)];//, (int)nCount];
    _lblDrowDownList.text = sInfo;
    [self showScanSheet];
}

- (void) showScanSheet {
    
    NSMutableDictionary *dirDevMember = [[NSMutableDictionary alloc] init];
    //NSInteger nCount = [_ncitBleDev connBLEDevCount:@"PE"];
    NSInteger nCount = [_ncitBleDev connBLEDevCount];
    for(NSInteger i=0; i<nCount; i++) {
        CBPeripheral *aPeripheral =[_ncitBleDev listBleDev:i];
        NSString* sBleName = aPeripheral.name;
        if (sBleName == nil || (![sBleName hasPrefix:@"PE"] && ![sBleName hasPrefix:@"COOBIT"])) {
            continue;
        }
        NSString* sId = aPeripheral.identifier.UUIDString;
        //NSString* sVal = sId;
        //[dirDevMember setValue: sBleName forKey:sId];
        [dirDevMember setObject: sBleName forKey:sId];
    }
    [_ddlBleDevice setListData:dirDevMember curSel:@"0"];
    [_ddlBleDevice popupDropDownList];
}

- (void) delayOpenScanSheet
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayOpenScanSheet) object:nil];
    if(_bChoseBleDev)
        return;
    
    //_lblMeasWgt.text = @"Scan Grs50 End...";
    //if([_ddlBleDevice isPopup])
        //return;
    
    [_ncitBleDev stopScan];
    
    //if(_ncitlLeDev.pBleDevSvr != nil)
        //return;
    
    if([_ncitBleDev connBLEDevCount:@"PE"] > 0) {
        //[self openScanSheet];
        [self showScanSheet];
         _lblDrowDownList.text = NSLocalizedString(@"Scan BLE Device End...", nil);
    }
    else {
        _lblDrowDownList.text = NSLocalizedString(@"No Any PEDO DEV Found!", nil);
        AudioServicesPlaySystemSound(1112);
    }
}

/*- (void) openScanSheet
{
    [self showScanSheet];
    _lblDrowDownList.text = @"Scan BLE Device End...";
}*/

- (NSString *) niDropDownDelegateMethod: (NIDropDownList *) sender
{
    _bChoseBleDev = YES;
    if(_ncitBleDev.m_pBleDevPer != nil) {
        _sCurBleConn = @"";
        _ddlBleDevice.sCurConnBLeDev = @"";
        [_ncitBleDev cancelPeripheralConnection];
    }
    
    _sCurrUuId = sender.sSelValId;
    _sCurBleConn = @"";
    
    
    //_bAutoConnect = YES;
    //_bJustScanGrs50 = NO;
    //_bFirstSelDev = YES;
    [_ddlBleDevice hideDropDownList];
    //_lblInfo.text = @"Selected";
    
    //CFStringRef uuidString = (__bridge CFStringRef)_sCurrUuId;
    //if([_sCurrUuId isEqual: (__bridge NSString *)uuidString])
    
    _ncitBleDev.bSyncDevData = YES;
    [_ncitBleDev addSavedDevice:_sCurrUuId tryConn: YES type:2 scan:NO];
    _lblDrowDownList.text = NSLocalizedString(@"Selected! please wait...", nil);
    
    NSString* sSelDev = sender.sSelText;
    _ncitBleDev.sStoredStepUuid = sSelDev;
    //[_ncitBLeDev connStoredBlePeripheral];
    
    return _sCurrUuId;
}

- (void) bleDevConnected:(NSString*)sUuid
{
    //_lblMeasWgt.text = @"WGT Ready, Use button to get WGT."
    ViewController* mainPage = [self findViewController:self];
    if(mainPage != nil) {
        _ncitBleDev.bleDelegate = nil;
        [mainPage bleDevConnected];    
        //[self removeFromSuperview];
      self.hidden = YES;
    }
}

- (ViewController *)findViewController:(UIView *)sourceView
{
    id target = sourceView;
    while (target) {
        target = ((UIResponder *)target).nextResponder;
        if ([target isKindOfClass:[ViewController class]]) {
            break;
        }
    }
    return target;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    /*CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGFloat rd = 15.0;
    CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect);
    CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy = CGRectGetMaxY(rect);
    
    CGContextSetRGBStrokeColor(ctx, 0.5, 0.1, 0.1, 1.0);
    
    CGContextSetLineWidth(ctx, 2.75);
    //drae rect
    CGContextMoveToPoint(ctx, minx, midy);
    // Add an arc through 2 to 3
    CGContextAddArcToPoint(ctx, minx, miny, midx, miny, rd);
    // Add an arc through 4 to 5
    CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, rd);
    // Add an arc through 6 to 7
    CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, rd);
    // Add an arc through 8 to 9
    CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, rd);
    // Close the path
    CGContextClosePath(ctx);
    // Fill & stroke the path
    CGContextDrawPath(ctx, kCGPathStroke);*/
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self close];
}

- (void) resetCtrls
{
  [self onTapDropDown];
  _lblDrowDownList.text = NSLocalizedString(@"Tap to choose device", nil);
}

- (BOOL) isPopup
{
    return [_ddlBleDevice isPopup];
}

- (void) close
{
    [_ddlBleDevice hideDropDownList];
}

@end
